import React from 'react'
import { Breadcrumb, Popconfirm, Modal, Popover, Input, Form, message, Table, Button } from 'antd'
import $ from 'jquery'
import Config from '../../common/config'
import server from '../server'
import './authority.less'

const config = new Config()
const FormItem = Form.Item
const token = sessionStorage.getItem('token')
let UserInfo = sessionStorage.getItem('UserInfo')
UserInfo = UserInfo ? JSON.parse(UserInfo) : {}
const root = UserInfo.root
const auth = root ? {} : (UserInfo.auth ? (UserInfo.auth[server.serverName] || {}) : {})
console.log(auth)
class Authority extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      authTree: [],//权限树data
      selectedNumber: null,//选择的权限number
      selectedName: null,//选择的权限name
      visible: false,//模态框
      type: 0,//  编辑:1  新增:2 服务:3
      // expandedRows: [],//展开的数据
    };
  }
  //获取权限树
  componentWillMount() {
    if (root || auth['/authority/setTree']) {
      this.getAuth().then(res => {
        console.log(res)
        if (res.code == 200) {
          this.setState({
            authTree: res.authority
          })
        } else if (res.code == 201) {
          message.info('获取数据失败')
        } else {
          message.info('服务器繁忙')
        }
      }).catch(err => {
        message.info('发生错误')
      })
    }
  }

  //获取权限树
  getAuth() {
    return Promise.resolve(
      $.ajax({
        url: config.Priviliege + '/authority/setTree',
        type: 'get',
        headers: { Authorization: 'Bearer ' + token }
      })
    )
  }
  //删除权限
  delAuth(number) {
    if (root || auth['/authority/delete']) {
      Promise.resolve(
        $.ajax({
          url: config.Priviliege + '/authority/delete',
          type: 'post',
          headers: { Authorization: 'Bearer ' + token },
          data: {
            number
          }
        })
      ).then(res => {
        console.log(res)
        if (res.code == 200) {
          return this.getAuth().then(res => {
            if (res.code == 200) {
              this.setState({
                authTree: res.authority
              }, () => {
                message.info('删除成功')
              })
            }
          })
        } else {
          message.info(
            `
            ${res.msg}:
            ${res.departmentArr ? '部门:' + res.departmentArr : ''}
            ${res.rolesArr ? '角色:' + res.rolesArr : ''}
            ${res.userArr ? '用户:' + res.userArr : ''}
            `
          )
        }
      }).catch(err => {
        console.log(err)
        message.info('发生错误')
      })
    }
  }

  //增加权限
  addAuth(number, name) {
    this.setState({
      selectedNumber: number,
      selectedName: name,
      visible: true,
      type: 2,
    })
  }

  //新增服务
  addServer() {
    this.setState({
      visible: true,
      type: 3,
    })
  }

  //编辑权限
  editAuth(number, name) {
    this.setState({
      selectedNumber: number,
      selectedName: name,
      visible: true,
      type: 1,
    })
  }

  //模态框取消
  handleCancel() {
    this.setState({
      selectedNumber: null,
      selectedName: null,
      visible: false,
      type: 0,
    })
  }

  //模态框确认
  handleOk() {
    const form = this.props.form
    form.validateFields((err, values) => {
      const { type, selectedNumber } = this.state
      const { newName, name, key, serverKey, serverName } = values
      if (!err) {
        return Promise.resolve().then(() => {
          if (type == 2) {//新增权限
            return $.ajax({
              url: config.Priviliege + '/authority/save',
              type: 'post',
              headers: { Authorization: 'Bearer ' + token },
              data: {
                name,
                key,
                fatherNumber: selectedNumber
              }
            })
          } else if (type == 1) { //更新权限名
            return $.ajax({
              url: config.Priviliege + '/authority/update',
              type: 'post',
              headers: { Authorization: 'Bearer ' + token },
              data: {
                number: selectedNumber,
                name: newName
              }
            })
          } else if (type == 3) { //新增服务
            return $.ajax({
              url: config.Priviliege + '/server/save',
              type: 'post',
              headers: { Authorization: 'Bearer ' + token },
              data: {
                name: serverName
              }
            })
          } else {
            return {}
          }
        }).then(res => {
          console.log(res)
          if (res.code == 200) {
            return this.getAuth().then(res => {
              if (res.code == 200) {
                this.setState({
                  selectedNumber: null,
                  selectedName: null,
                  visible: false,
                  type: 0,
                  authTree: res.authority
                }, () => {
                  message.info('操作成功')
                  form.resetFields()
                })
              }
            })
          } else if (res.code == 201) {
            message.info(res.msg)
          } else {
            message.info('服务器繁忙')
          }
        }).catch(err => {
          message.info('发生错误')
        })
      }
    });
  }

  // expandedRows(expandedRows) {
  //   this.setState({
  //     expandedRows
  //   })
  // }

  formSon(getFieldDecorator) {
    const { type, selectedName } = this.state
    if (type == 2) {
      return (
        <div style={{ paddingTop: 20 }}>
          <Input className="lasttrees" addonBefore="父级权限" value={selectedName} disabled />
          <p style={{ height: 20 }}>&nbsp;</p>
          <FormItem label='权限key:' >
            {getFieldDecorator('key', {
              rules: [
                { max: 50, message: '长度不能超过50' },
                { required: true, message: '请输入权限key' },
                { pattern: /^(?=^(v\-|\/))^[a-zA-Z0-9\u4e00-\u9fa5\d\-\/_]+$/, message: `key必须以'v-'或'/'开头` }
              ],
            })(
              <Input
                onChange={(e) => { e.target.value = $.trim(e.target.value).replace(' ', '') }}
              />
            )}
          </FormItem>
          <FormItem label='权限名称:'>
            {getFieldDecorator('name', {
              rules: [
                { required: true, message: '请输入权限名称' },
                { max: 15, message: '长度不能超过15' },
              ],
            })(
              <Input
                onChange={(e) => { e.target.value = $.trim(e.target.value).replace(' ', '') }}
              />
            )}
          </FormItem>
        </div>
      )
    } else if (type == 1) {
      return (
        <div style={{ paddingTop: 20 }}>
          <Input className="lasttrees" addonBefore="原权限名称" value={selectedName} disabled />
          <p style={{ height: 20 }}>&nbsp;</p>
          <FormItem label='新权限名称'>
            {getFieldDecorator('newName', {
              rules: [
                { max: 15, message: '长度不能超过15' },
                { required: true, message: '请输入新权限名' }
              ],
            })(
              <Input
                onChange={(e) => { e.target.value = $.trim(e.target.value).replace(' ', '') }}
              />
            )}
          </FormItem>
        </div>
      )
    } else if (type == 3) {
      return (
        <div>
          {/* <FormItem label='服务权限key:'>
            {getFieldDecorator('serverKey', {
              rules: [{ required: true, message: '请输入服务权限key' }],
            })(
              <Input />
            )}
          </FormItem> */}
          <FormItem label='服务名称:'>
            {getFieldDecorator('serverName', {
              rules: [
                { max: 15, message: '长度不能超过15' },
                { required: true, message: '请输入服务名称' }
              ],
            })(
              <Input
                onChange={(e) => { e.target.value = $.trim(e.target.value).replace(' ', '') }}
              />
            )}
          </FormItem>
        </div>
      )
    }
  }
  render() {
    const columns = [
      {
        title: '权限名称',
        key: 'name',
        width: '70%',
        render: (record) => {
          return (
            <Popover content={record.key} trigger="hover">
              <span>{record.name}</span>
            </Popover>
          )
        }
      },
      {
        title: '操作',
        key: 'action',
        width: '30%',
        className: 'lastaction',
        render: (record) => {
          if (root) {
            return (
              <div>
                <span
                  className='todoAction'
                  style={{ marginLeft: 10 }}
                  onClick={this.addAuth.bind(this, record.number, record.name)}
                >新增子集</span>
                <span
                  className='todoAction'
                  style={{ marginLeft: 10 }}
                  onClick={this.editAuth.bind(this, record.number, record.name)}
                >编辑名称</span>
                <Popconfirm
                  title="确认删除吗?"
                  onConfirm={this.delAuth.bind(this, record.number)}
                  okText="确认"
                  cancelText="取消"
                >
                  <span
                    className='todoAction'
                    style={{ marginLeft: 10 }}
                  >删除</span>
                </Popconfirm>
              </div>
            )
          }
          if (/^fw-[1-9]*$/.test(record.number)) {
            return (
              <div>
                {auth['/authority/save'] ?
                  <span
                    className='todoAction'
                    style={{ marginLeft: 10 }}
                    onClick={this.addAuth.bind(this, record.number, record.name)}
                  >新增子集</span>
                  : ''
                }
                {auth['/authority/update'] ?
                  <span
                    className='todoAction'
                    style={{ marginLeft: 10 }}
                    onClick={this.editAuth.bind(this, record.number, record.name)}
                  >编辑名称</span>
                  : ''
                }
              </div>
            )
          }
          return (
            <div>
              {auth['/authority/save'] ?
                <span
                  className='todoAction'
                  style={{ marginLeft: 10 }}
                  onClick={this.addAuth.bind(this, record.number, record.name)}
                >新增子集</span>
                : ''
              }
              {auth['/authority/update'] ?
                <span
                  className='todoAction'
                  style={{ marginLeft: 10 }}
                  onClick={this.editAuth.bind(this, record.number, record.name)}
                >编辑名称</span>
                : ''
              }
              {auth['/authority/delete'] ?
                <Popconfirm
                  title="确认删除吗?"
                  onConfirm={this.delAuth.bind(this, record.number)}
                  okText="确认"
                  cancelText="取消"
                >
                  <span
                    className='todoAction'
                    style={{ marginLeft: 10 }}
                  >删除</span>
                </Popconfirm>
                : ''
              }
            </div>
          )
        }
      }
    ];
    const { getFieldDecorator } = this.props.form
    return (
      <div className='container' >
        <div className="box">
          <div className='breadcrumb'>
            <Breadcrumb separator=">">
              <Breadcrumb.Item>权限设置</Breadcrumb.Item>
              <Breadcrumb.Item>权限管理</Breadcrumb.Item>
            </Breadcrumb>
          </div>
          {root ? <Button className='member-button-aa' type='primary' onClick={this.addServer.bind(this)} style={{ marginBottom: 20, }}>新增服务</Button> : null}
          {
            (root || auth['/authority/setTree']) ?
              <div>
                {
                  (this.state.authTree && this.state.authTree.length) ? <Table
                    rowKey="number"
                    columns={columns}
                    dataSource={this.state.authTree}
                    pagination={false}
                    bordered
                    defaultExpandAllRows
                    className="lastsee"
                  // onExpandedRowsChange={this.expandedRows.bind(this)}
                  /> : ''
                }
              </div>
              :
              ''
          }
        </div>
        <Modal
          visible={this.state.visible}
          title={
            this.state.type == 1 ? '编辑权限名' : (this.state.type == 2 ? '新增权限' : '新增服务')
          }
          width={400}
          maskClosable={false}
          onCancel={this.handleCancel.bind(this)}
          onOk={this.handleOk.bind(this)}
        >
          <Form>
            {
              this.formSon(getFieldDecorator)
            }
          </Form>
        </Modal>
      </div>
    );
  }
}
const AuthorityForm = Form.create()(Authority);
export default AuthorityForm;